<!--
@description ：敏感行为监控
-->

<template>
  <div class="app-container">
    <el-card>
      <h3>敏感行为监控</h3>
    </el-card>
    <el-card style="margin-top: 20px;">
      <NormalForm :enumOpt="enumOpt" :formList="formList" :isShowCard="false" :operateForm="queryForm"
                  pageTitle=""
                  @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
    </el-card>
    <el-card style="margin-top: 20px;">
      <el-row class="header-search">
        <el-col :span="18">
          <el-radio-group v-model="queryForm.timeType" style="display: flex;justify-content: space-between;width: 360px"
                          @input="radioDateSelect(queryForm.timeType)">
            <div v-for="item in timeTypeList" :key="item.dictValue">
              <el-radio-button :label="item.dictValue">{{ item.dictLabel }}</el-radio-button>
            </div>
          </el-radio-group>
        </el-col>
        <el-col :span="6" style="text-align: end">
          <el-button type="primary" @click="setBehaviorConfig" v-has-permi="['risk:monitor:add']">监控行为设置</el-button>
          <el-button type="primary" @click="setEndConfig" v-has-permi="['risk:language:list']">正常结束语设置</el-button>
        </el-col>
      </el-row>
      <div style="margin-top: 12px">
        <el-table v-loading="loading" :data="tableList" max-height="560" min-height="420" style="width: 100%" v-has-permi="['risk:monitor:list']">
          <el-table-column :show-overflow-tooltip="false" align="center" label="触发员工" min-width="140"
                           prop="weUserName">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="false" align="center" label="聊天客户" min-width="140"
                           prop="wechatNickname">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="center" label="敏感操作类型" min-width="140"
                           prop="sensitiveBehaviorName">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="false" align="center" label="触发时间" min-width="170"
                           prop="triggerTime">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="false" align="center" label="处理人" min-width="140"
                           prop="handleUser">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="false" align="center" label="处理时间" min-width="170"
                           prop="handleTime"></el-table-column>
          <el-table-column :show-overflow-tooltip="false" align="center" label="处理结果" min-width="150"
                           prop="handleResult">
            <template slot-scope="scope">
              <span style="margin-right: 12px">{{ scope.row.handleResultName }}</span>
              <div style="display: inline-block" v-if="scope.row.handleStatus == '1' && scope.row.remark">
                <el-tooltip :content="scope.row.remark" effect="dark" placement="top">
                  <span>备注</span>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作"
                           width="140">
            <template slot-scope="{ row }">
              <div style="display: flex; justify-content: space-around">
                <el-button size="mini" v-has-permi="['risk:monitor:handle']" type="text" @click="toDispose(row)" :disabled="row.handleStatus == 1" :style="`color: ${ row.handleStatus == 1 ? '#cccccc' : '#082AFF' }!important`">处理
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                          @handleCurrentChange="handleCurrentChange" :page-size-list="pageSizeList"
                          @handleSizeChange="handleSizeChange"></NormalPagination>
      </div>
    </el-card>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="true"
               :visible.sync="disposeVisible"
               title="处理操作" width="520px">
      <el-form ref="disposeForm" :model="disposeForm" :rules="rules" label-width="120px">
        <el-form-item label="处理结果" prop="handleResult">
          <el-radio-group v-model="disposeForm.handleResult">
            <el-radio label="0">合规</el-radio>
            <el-radio label="1">违规</el-radio>
            <el-radio label="2">忽略</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="disposeForm.remark" clearable maxlength="200" rows="4" show-word-limit
                    type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelDispose" :loading="saveLoading">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" @click="saveDispose">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="true" :show-close="true"
               :visible.sync="setConfigVisible" append-to-body
               title="监控行为设置" width="600px">
      <el-form :model="setConfigForm" label-width="82px" ref="setConfigForm">
        <el-form-item label="敏感行为:" prop="sensitiveBehavior">
          <el-checkbox-group v-model="setConfigForm.sensitiveBehavior">
            <el-checkbox label="1">撤回消息</el-checkbox>
            <el-checkbox label="2">超时回复</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div v-show="setConfigForm.sensitiveBehavior.indexOf('2') > -1">
          <div v-for="(item, index) in setConfigForm.monitorList" :key="index" class="monitoringListItem">
            <el-row style="line-height: 30px">
              <el-col :span="12" style="color: #505050;font-weight: 500">{{ `超时监控组${index + 1}` }}</el-col>
              <el-col :span="12" style="text-align: end">
                <el-button style="color: #0079FE;" type="text" @click.native="addMonitoringListItem(item,index)">添加
                </el-button>
                <el-button v-if="setConfigForm.monitorList.length > 1" style="color: #082AFF;margin-left: 8px"
                           type="text" @click.native="delMonitoringListItem(item,index)">删除
                </el-button>
              </el-col>
            </el-row>
            <el-form-item class="showRedRules" label="监控时间:">
              <el-select v-model="item.cycle" clearable multiple style="width: 360px" @visible-change="loadOptions">
                <el-option v-for="w in showWeekdayList" :key="w.value" :disabled="w.disabled" :label="w.label"
                           :value="w.value"></el-option>
              </el-select>
            </el-form-item>
            <div v-for="(itm, ind) in item.monitorTime" :key="ind" class="monitoringTimeItem">
              <el-form-item :label="`时间${ind + 1}:`" style="position: relative">
                <el-time-picker
                  v-model="item.monitorTime[ind][0]"
                  :picker-options="pickerOptions"
                  placeholder="开始时间"
                  style="width: 114px"
                  type="datetime"
                  value-format="HH:mm">
                </el-time-picker>
                <span style="width:32px;display: inline-block;text-align: center;font-size: 18px">至</span>
                <el-time-picker
                  v-model="item.monitorTime[ind][1]"
                  :picker-options="pickerOptions"
                  placeholder="结束时间"
                  style="width: 114px"
                  type="datetime"
                  value-format="HH:mm">
                </el-time-picker>
                <i v-if="item.monitorTime.length != 1" class="el-icon-remove-outline conIcon"
                   style="margin-left: 8px;  position: absolute;bottom: 6px;left: 284px;color: #F23031"
                   @click="item.monitorTime.splice(ind, 1)"></i>
                <i class="el-icon-circle-plus-outline conIcon"
                   style="margin-left: 8px;position: absolute;bottom: 6px;left: 260px"
                   @click="item.monitorTime.push([])"></i>
              </el-form-item>
            </div>
            <span class="monitoringListItem-info">设置后，将会监控该时间段内员工对客户的回复时长</span>
            <el-form-item class="showRedRules" label="超时界定:">
              超过
              <el-time-picker
                v-model="item.timeout"
                :picker-options="pickerOptions"
                formatter="HH:mm"
                placeholder="超时时间"
                style="width: 114px;margin: 0 6px"
                type="datetime"
                value-format="HH:mm">
              </el-time-picker>
              未回复
            </el-form-item>
            <span class="monitoringListItem-info">针对客户最近消息的回复状态，超过界定时间未回复，将视为超时回复</span>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="setConfigVisible = false" :loading="setConfigLoading">取 消</el-button>
        <el-button :loading="setConfigLoading" type="primary" @click="saveConfig">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="delvisible" title="删除确认" top="15% !important" width="320px">
      <div style="text-align: center;height: 50px;line-height: 50px;">
        <i class="el-icon-question"
           style="color: #082AFF;margin-right: 10px;"></i><span>删除操作不可恢复，确认继续删除?</span>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button :loading="delloading" size="mini" @click="delvisible = false">取 消</el-button>
        <el-button :loading="delloading" size="mini" type="primary" @click="deleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import * as api from "@/api/organization";
import * as $api from '@/api/riskManager/behavior'
import {handleMonitor} from "@/api/riskManager/behavior";

export default {
  name: "sensitiveBehaviorMonitoring", //页面名称，必填
  props: {},
  components: {},
  data() {
    return {
      queryForm: {
        weUserId: [],
        dateRange: [],
        sensitiveBehavior: null,
        handleStatus: null,
        handleResult: null,
        timeType: '0',
        pageNum: 1,
        pageSize: 10,
      },
      formList: [
        {
          label: '触发员工',
          value: [],
          prop: 'weUserId',
          type: 'SELECT',
          emunName: 'weUserIdList',
          multiple: false,
          defaultNoLabel: true,
        },
        {
          label: '',
          value: [],
          prop: 'dateRange',
          type: 'DATE_RANGE',
          formate: 'yyyy-MM-dd',
          emunName: '',
          xs: 24,
          ls: 12,
          md: 10,
          lg: 8,
          xl: 6,
        },
        {
          label: '敏感操作',
          value: '',
          prop: 'sensitiveBehavior',
          type: 'SELECT',
          multiple: false,
          emunName: 'behaviorList',
          defaultNoLabel: true,
        },
        {
          label: '处理状态',
          value: '',
          prop: 'handleStatus',
          type: 'SELECT',
          emunName: 'handleStatusList',
          defaultNoLabel: true,
        },
        {
          label: '处理结果',
          value: '',
          prop: 'handleResult',
          type: 'SELECT',
          emunName: 'handleResultList',
          defaultNoLabel: true,
        },
      ], // 查询框
      enumOpt: {
        weUserIdList: [],
        behaviorList: [
          {dictValue: '1', dictLabel: '撤回消息'},
          {dictValue: '2', dictLabel: '超时回复'},
        ],
        handleStatusList: [
          {dictValue: '0', dictLabel: '未处理'},
          {dictValue: '1', dictLabel: '已处理'},
        ],
        handleResultList: [
          {dictValue: '0', dictLabel: '合规'},
          {dictValue: '1', dictLabel: '违规'},
          {dictValue: '2', dictLabel: '忽略'},
        ],
      },
      timeTypeList: [
        {dictValue: '0', dictLabel: '全部'},
        {dictValue: '1', dictLabel: '最近7天'},
        {dictValue: '2', dictLabel: '最近30天'},
        {dictValue: '3', dictLabel: '最近90天'},
      ],
      loading: false,
      tableList: [],
      pageSizeList: [10,20,30,50],
      total: 0,

      recordId: '',
      disposeVisible: false, // 处理弹窗设置
      disposeForm: {
        handleResult: '',
        remark: '',
      },
      rules: {
        handleResult: [{required: true, message: '请选择处理结果', trigger: 'change'}],
      },
      saveLoading: false,

      setConfigVisible: false, // 监控行为设置
      setConfigForm: {
        sensitiveBehavior: [],
        monitorList: [
          {
            cycle: [],
            monitorTime: [[]],
            timeout: '',
          }
        ],
      },
      setConfigLoading: false,
      pickerOptions: {
        format: 'HH:mm',
        'value-format': 'HH:mm',
        defaultValue: new Date(0, 0, 0, 0, 0, 0),
      },

      weekdayList: [
        {value: '1', label: '周一', disabled: false},
        {value: '2', label: '周二', disabled: false},
        {value: '3', label: '周三', disabled: false},
        {value: '4', label: '周四', disabled: false},
        {value: '5', label: '周五', disabled: false},
        {value: '6', label: '周六', disabled: false},
        {value: '7', label: '周日', disabled: false}
      ],
      showWeekdayList: [],

      delvisible: false,
      delloading: false,
      currentRowIndex: '',
    }
  },
  watch: {},
  computed: {},
  methods: {
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getListFn()
    },
    handleReset() {
      this.queryForm = {
        weUserIdList: [],
        startTime: '',
        endTime: '',
        dateRange: [],
        sensitiveBehavior: null,
        handleStatus: null,
        handleResult: null,
        timeType: '0',
        pageNum: 1,
        pageSize: 10,
      }
      this.radioDateSelect('0')
    },
    getListFn() {
      let obj = {
        weUserIdList: this.queryForm.weUserIdList,
        triggerCreateTime: this.queryForm.dateRange?.[0],
        triggerEndTime: this.queryForm.dateRange?.[1],
        sensitiveBehavior: this.queryForm.sensitiveBehavior,
        handleStatus: this.queryForm.handleStatus,
        handleResult: this.queryForm.handleResult,
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
      }
      this.loading = true
      this.tableList = []
      $api.getMonitorList(obj).then(res => {
        if(res.code == 200){
          this.tableList = res.rows
          this.total = res.total
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.getListFn()
    },
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getListFn()
    },
    // 日期单选框
    radioDateSelect(val) {
      let da = 0
      if (val == '0') {
        da = 0
      } else if (val == '1') {
        da = 7
      } else if (val == '2') {
        da = 30
      } else if (val == '3') {
        da = 90
      }
      let currentDate = new Date();
      let nowDate = new Date()
      nowDate.setHours(23, 59, 59, 59)
      let endDate = currentDate.toISOString().substring(0, 10)
      currentDate.setHours(0, 0, 0, 0); // 将时间设置为当天的凌晨
      // let endDate = currentDate.toISOString().substring(0, 10); // 当天的日期作为结束日期
      currentDate.setDate(currentDate.getDate() - da + 1); // 将日期设置为需要的天数
      let startDate = currentDate.toISOString().substring(0, 10); // 将设置的天数作为开始日期
      let datesArray = [startDate, endDate]
      if (da != 0) {
        this.queryForm.dateRange = datesArray
        this.$set(this.queryForm, 'dateRange', datesArray)
      } else {
        this.queryForm.dateRange = []
        this.$set(this.queryForm, 'dateRange', [])
      }
      this.getListFn()
    },
    // 监控行为设置
    setBehaviorConfig() {
      $api.queryMonitor().then(res => {
        console.log('获取配置的监控行为:::::', res)
        if(res.code == 200){
          this.setConfigForm.sensitiveBehavior = res.data.sensitiveBehavior.split(',')
          this.$set(this.setConfigForm, 'sensitiveBehavior', this.setConfigForm.sensitiveBehavior)
          this.setConfigForm.monitorList = res.data.monitorList && res.data.monitorList.length > 0 ? res.data.monitorList.map((item, index) => {
            let obj = {
              cycle: item.cycle.split(','),
              monitorTime: item.monitorTime && item.monitorTime.length > 0 ? item.monitorTime.map(i => {
                return i.split(',')
              }) : [],
              timeout: item.timeout
            }
            this.$set(this.setConfigForm.monitorList, index, obj)
            return obj
          }) : []
          this.loadOptions(true)
          this.$forceUpdate()
          console.log('setConfigForm:::::::', this.setConfigForm)
        }
      })
      window.setTimeout(() => {
        this.setConfigVisible = true
      }, 100)
    },
    // 正常结束语设置
    setEndConfig() {
      this.$router.push({
        name: 'SensitiveBehaviorMonitoringEnding',
        query: {}
      })
    },
    // 处理
    toDispose(row) {
      if(row.handleStatus == 1) return
      this.disposeVisible = true
      this.recordId = row.recordId
      this.disposeForm = {
        handleResult: '',
        remark: '',
      }
      this.$nextTick(() => {
        this.$refs['disposeForm'].clearValidate()
      })
    },
    cancelDispose() {
      this.disposeVisible = false
    },
    saveDispose() {
      let obj = {
        recordId: this.recordId,
        ...this.disposeForm
      }
      this.$refs.disposeForm.validate(valid => {
        if(valid){
          $api.handleMonitor(obj).then(res => {
            if(res.code == 200){
              this.disposeVisible = false
              this.$message.success('处理成功')
              this.handleQuery()
            }
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },

    // 添加监控组配置
    addMonitoringListItem(item, index) {
      this.setConfigForm.monitorList.push({
        cycle: [],
        monitorTime: [[]],
        timeout: '',
      })
    },
    // 减少监控组配置
    delMonitoringListItem(item, index) {
      this.delvisible = true
      this.currentRowIndex = index
    },
    deleteConfirm(){
      this.setConfigForm.monitorList.splice(this.currentRowIndex, 1)
    },
    // 监控时间枚举值实时变化
    loadOptions(visible) {
      if (visible) {
        this.showWeekdayList = this.weekdayList.map(item => ({
          ...item,
          disabled: this.setConfigForm.monitorList.some(obj => obj?.cycle.indexOf(item.value) > -1)
        }))
      }
    },
    // 保存监控组配置
    saveConfig() {
      console.log('监控组配置信息:::::', this.setConfigForm)
      const list = this.setConfigForm.monitorList
      if (list && list.length > 0) {
        if (list.some(obj => !obj.cycle || obj.cycle.length == 0)) {
          const index = list.findIndex(obj => !obj.cycle || obj.cycle.length == 0)
          return this.$message.error(`超时监控组${index + 1}的监控时间未设置！`)
        }
        for (let i = 0; i < list.length; i++) {
          for (let x = 0; x < list[i].monitorTime.length; x++) {
            const arr = list[i].monitorTime[x]
            if (arr.length == 0) {
              return this.$message.error(`超时监控组${i + 1}的时间${x + 1}未设置！`)
            }
            if (!arr[0]) {
              return this.$message.error(`超时监控组${i + 1}的时间${x + 1}的开始时间未设置！`)
            }
            if (!arr[1]) {
              return this.$message.error(`超时监控组${i + 1}的时间${x + 1}的结束时间未设置！`)
            }
            let today = new Date();
            let date1 = new Date(today.toDateString() + " " + arr[0])
            let date2 = new Date(today.toDateString() + " " + arr[1])
            if (date1 > date2) {
              return this.$message.error(`超时监控组${i + 1}的时间${x + 1}的结束时间必须大于开始时间！`)
            }
          }
        }
        if (list.some(obj => !obj.timeout)) {
          const index = list.findIndex(obj => !obj.timeout)
          return this.$message.error(`超时监控组${index + 1}的超时界定未设置！`)
        }
      }
      console.log('通过校验::::::::::', this.setConfigForm)
      this.setConfigLoading = true
      let obj = {
        sensitiveBehavior: this.setConfigForm.sensitiveBehavior.toString(),
        monitorList: this.setConfigForm.monitorList.map(item => {
          return {
            cycle: item.cycle.toString(),
            monitorTime: item.monitorTime.map(i => i.toString()),
            timeout: item.timeout
          }
        })
      }
      $api.addMonitor(obj).then(res => {
        if(res.code == 200){
          this.setConfigVisible = false
          this.$message.success('监控行为设置成功')
        }
        this.setConfigLoading = false
      }).catch(() => {
        this.setConfigLoading = false
      })
    },
  },
  mounted() {
    api.getList({
      name: '',
      department: '',
      pageNum: 1,
      pageSize: 99999,
      isActivate: '',
    })
      .then(({rows}) => {
        const data = rows.map(item => {
          return {
            dictLabel: `${item.name}(${item.isOpenChat == 1 ? '开启' : '未开启'}会话留存)`,
            dictValue: item.userId,
            disabled: item.isOpenChat == 0,
          }
        })
        this.enumOpt.weUserIdList = JSON.parse(JSON.stringify(data))
      })
    this.handleQuery()
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

.app-container {
  height: 100%;
}

::v-deep {
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: #082AFF;
    border-color: #082AFF;
    background: transparent;
    -webkit-box-shadow: -1px 0 0 0 #082AFF;
    box-shadow: -1px 0 0 0 #082AFF;
  }

  .el-input-number.is-controls-right .el-input__inner {
    text-align: left;
  }
}

.header-search {
  padding-top: 10px;
}

.monitoringListItem {
  padding: 8px 16px 16px;
  border-radius: 4px;
  margin: 0 24px 18px;
  background: #EEEEEE;
}

.showRedRules {
  ::v-deep.el-form-item__label:before {
    content: '*';
    color: #e74e59;
    margin-right: 4px;
  }
}

.monitoringTimeItem {
  margin-left: 52px;
}

.monitoringListItem-info {
  margin-left: 92px;
  color: #999999;
  font-size: 10px;
  line-height: 18px;
}

.conIcon {
  font-size: 16px;
  cursor: pointer;
}
</style>
